package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 拆分的多线程处理的工具类
 *    1、交给容器管理
 *    2、在方法上配置注解，表明多线程执行
 */
@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *  @Async:异步处理，相当于创建了一个Thread执行
     */
    @Async("threadPool")
    public void saveTimeLine(Long userId, ObjectId movementId) {
        //模拟5秒发布
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String name = Thread.currentThread().getName();
        System.out.println("线程池名称="+name);
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        //后续版本中，可以在这里排除不可见的好友
        //3、一个好友，构造一个动态-好友关系数据
        for (Friend friend : list) {
            MovementTimeLine line = new MovementTimeLine();
            line.setMovementId(movementId);
            line.setUserId(userId);
            line.setFriendId(friend.getFriendId());
            line.setCreated(System.currentTimeMillis());
            mongoTemplate.save(line);
        }
    }
}
